package com.tianyang.yukuaifuzs.rxservice;

import android.text.TextUtils;

import androidx.core.util.Pair;

import com.tianyang.yukuaifuzs.common.interfaces.CommonConfig;
import com.tianyang.yukuaifuzs.common.interfaces.UrlConstants;
import com.tianyang.yukuaifuzs.utils.TimeManager;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import rx.Observable;

/**
 * Description：带文件上传的网络接口基类 retrofit2 & RxJava & Http
 * Created by 薛勇军 on 2020/7/17
 */
public class BaseUploadClient {

    private HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    protected OkHttpClient client;
    private Interceptor headInterceptor;

    protected BaseUploadClient() {
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        headInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request()
                        .newBuilder()
                        .addHeader("timestamp", String.valueOf(TimeManager.getInstance().getCurTimeMillis()))
                        .build();
                return chain.proceed(request);
            }
        };

        client = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .addInterceptor(headInterceptor)
                .readTimeout(UrlConstants.HTTP_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(UrlConstants.HTTP_TIMEOUT, TimeUnit.SECONDS)
                .build();
    }
//
//    /**
//     * response处理
//     *
//     * @param observable 对象
//     */
//    public Observable<Pair<MetaBean, String>> callMap(Observable<MetaBean> observable) {
//        return observable.map(new Func1<MetaBean, Pair<MetaBean, String>>() {
//            @Override
//            public Pair<MetaBean, String> call(MetaBean metaBean) {
//                if (metaBean == null) {
//                    return null;
//                }
//                if (TextUtils.equals(CommonConfig.RET_OK, metaBean.getCode())) {
//                    if (!TextUtils.isEmpty(metaBean.getData())) {
//                        //解密
//                        try {
//                            String respData = metaBean.getData();
//                            Log.e(metaBean.getMessage(), respData);
//                            return new Pair<>(metaBean, respData);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        return new Pair<>(metaBean, null);
//                    }
//                }
//                return new Pair<>(metaBean, "");
//            }
//        });
//    }

    /**
     * 创建Obserable
     */
    public <T> Observable<T> toObservable(Pair<MetaBean, T> pair) {
        if (pair == null || pair.first == null) {
            return Observable.error(RxError.create(RxError.ERROR_UNKNOWN, RxError.ERROR_UNKNOWN));
        }
        if (TextUtils.equals(CommonConfig.RET_OK, String.valueOf(pair.first.getCode()))) {
            return Observable.just(pair.second);
        }
        if (TextUtils.equals(CommonConfig.OFFLINE, String.valueOf(pair.first.getCode()))) {
            return Observable.error(RxError.create(RxError.ERROR_OFFLINE, String.valueOf(pair.first.getCode()),
                    pair.first.getMessage()));
        }
        return Observable.error(RxError.create(RxError.ERROR_TYPE_DATA, String.valueOf(pair.first.getCode()),
                pair.first.getMessage()));
    }

    /**
     * 文件上传处理
     * @param filePaths 文件地址集合
     */
    protected List<MultipartBody.Part> files2Parts(HashMap<String, File> filePaths) {
        if (filePaths != null && !filePaths.isEmpty()) {
            List<MultipartBody.Part> parts = new ArrayList<>(filePaths.size());
            for (Map.Entry<String, File> entry : filePaths.entrySet()) {
                File file = entry.getValue();
                RequestBody requestBody = RequestBody.create(MediaType.parse("image"), file);
                MultipartBody.Part part = MultipartBody.Part.
                        createFormData(entry.getKey(), file.getName(), requestBody);
                parts.add(part);
            }
            return parts;
        }
        return null;
    }
}
